var userID;
var token;

$(document).ready(initialize);

function addTag(event, ui) {
	if(ui.duringInitialization)
		return;

	$.ajax({
		url: '/resources/searchPhrase/match',
		type: 'POST',
		data: ui.tagLabel,
		statusCode: {
			200: function(data) {
				$("#removedP").hide();
				$("#addedTerm").html(data);
				$("#addedP").show();
			},
			401: function(data) {
				showSignedOutDiv();
			}
		}
	});
}

function beginSearch() {
	showSearchButtonAsSearching();

	$.ajax({
		url: 'resources/searchPhrase/search/',
		type: 'GET',
		statusCode: {
			200: function(data) {
				if(data.token != null && data.token.length > 0) {
					$.cookie('token', data.token);
				} else if(data.matchedFollowers != null && data.matchedFollowers.length > 0) {
					showSearchButtonAsDisabled();
				}
			},
			401: function(data) {
				showSignedOutDiv();
			}
		}
	});
}

function checkForSeachResults() {
	showSearchButtonAsSearching();
		
	$.ajax({
		url: 'resources/searchPhrase/check/',
		type: 'GET',
		statusCode: {
			200: function(data) {
				if(data.length > 0) {
					displayMatchedFollowers(data);
				} else {
					showSearchButtonAsNormal();
				}
			},
			401: function(data) {
				showSignedOutDiv();
			}
		}
	});
}

function deleteTag(event, ui) {
	if(ui.duringInitialization)
		return;

	$.ajax({
		url: '/resources/searchPhrase/remove',
		type: 'DELETE',
		data: ui.tagLabel,
		statusCode: {
			200: function(data) {
				$("#addedP").hide();
				$("#removedTerm").html(ui.tagLabel);
				$("#removedP").show();
			}
		}
	});
}

function displayMatchedFollowers(data) {
	showSearchButtonAsDisabled();
	var resultsDivHTML = '';
	$.each(data, function(index, matchedFollower){
		resultsDivHTML += '<div class="result-div" id="resultDiv' +matchedFollower.id+ '">' +
								'<div style="height:80px">'+
									'<img class="result-div-profile-pic" src="' +matchedFollower.pictureURL+ '"> ' +
									'<span class="result-div-screenname">' +matchedFollower.screenName+ '</span><br/>' +
									'<span class="result-div-description">' +matchedFollower.description.value+ '</span><br/>' +
								'</div>'+
								'<div class="result-div-buttons">'+
									'<a class="btn btn-success" href="#" onclick="followResult(\'' +matchedFollower.id+ '\'); return false;"><i class="icon-twitter"></i> Follow</a> <a class="btn btn-danger" href="#" onclick="removeResult(\'' +matchedFollower.id+ '\'); return false;"><i class="icon-remove"></i> Remove</a>'+
								'</div>'+
							'</div>';
	});
	$('#followerDisplayDiv').append(resultsDivHTML);
}

function followResult(id) {
	$.ajax({
		url: '/resources/friend/follow/' +id,
		type: 'POST',
		statusCode: {
			200: function(data) {
				$('#resultDiv' +id).hide();
			},
			401: function(data) {
				showSignedOutDiv();
			}
		}
	});
}

function getFollowers() {
	$.ajax({
		url: 'resources/user/followers/',
		type: 'GET',
		statusCode: {
			200: function(data) {
				$('#followerLoader').hide();
				$('#actualFollowers').html(data);
			}
		}
	});
}

function initialize() {
	// add listeners
	$('#searchButton').click(beginSearch);

	userID = $.cookie('userID');
	token = $.cookie('token');

	// if no userID, authenticate
	if(userID == null) {
		$.ajax({
			url: 'resources/oauth/check/',
			type: 'GET',
			statusCode: {
				200: function(data) {
					$.cookie('userID', data.id);
					$.cookie('screenname', data.name);
					$.cookie('profilePic', data.picture);
					$.cookie('token', data.token);
					showSignedInDiv();
					
					// if token found, check for search results
					if(token != null && token.length > 0) {
						checkForSeachResults();
					}
				},
				401: function(data) {
					showSignedOutDiv();
				}
			}
		});
	} else {
		showSignedInDiv();
		
		// if token found, check for search results
		if(token != null && token.length > 0) {
			checkForSeachResults();
		}
	}
}

function openConnectionForSearchResults() {
	var channel = new goog.appengine.Channel($.cookie('token'));
	channel.open({
		onopen: function(message) {},
		onmessage: function(message) {
			var responseJSON = JSON.parse(message.data);
			displayMatchedFollowers(responseJSON);
		},
		onerror: function() {},
		onclose: function() {}
	})
}

function showSearchButtonAsDisabled() {
	$('#searchButton').attr('disabled', 'disabled');
	$('#searchSpinner').hide();
}

function showSearchButtonAsNormal() {
	$('#searchButton').removeAttr('disabled');
	$('#searchSpinner').hide();
}

function showSearchButtonAsSearching() {
	$('#searchButton').attr('disabled', 'disabled');
	$('#searchSpinner').show();
}

function showSignedInDiv() {
	userID = $.cookie('userID');
	token = $.cookie('token');

	$('#signedOutDiv').hide();
	$('#signedInDiv').show();
	$('#screenname').html($.cookie('screenname'));
	$('#profilePic').attr("src", $.cookie('profilePic'));
	
	getMatches();
}

function showSignedOutDiv() {
	$('#signedOutDiv').show();
	$('#signedInDiv').hide();
}

function removeResult(id) {
	$.ajax({
		url: '/resources/friend/remove/' +id,
		type: 'DELETE',
		statusCode: {
			200: function(data) {
				$('#resultDiv' +id).hide();
			},
			401: function(data) {
				showSignedOutDiv();
			}
		}
	});
}

function getMatches() {
	$.ajax({
		url: 'resources/searchPhrase/get/',
		type: 'GET',
		statusCode: {
			200: function(data) {
				$.each(data, function(index, searchPhrase) {
					$("#myTags").append('<li>' +searchPhrase+ '</li>')
				});
				
				$("#myTags").tagit({
					allowSpaces: true,
					afterTagAdded: addTag,
					afterTagRemoved: deleteTag
				});
			},
			401: function(data) {
				showSignedOutDiv();
			}
		}
	});
}